﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.InvoiceManagements;
using Reporting.Domain;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.InvoiceManagements;

namespace Reporting.API.Application.CommandHandler.InvoiceManagements
{
    /// <summary>
    /// 开票ID查询
    /// </summary>
    public class GetIDInvoiceManagementCommandHandler : IRequestHandler<GetIDInvoiceManagementCommand, ApiResult<InvoiceManagement>>
    {
        private readonly IInvoiceManagementRepository _invoiceManagementRepository;  //开票
        private readonly IMapper _mapper;
        private readonly ILogger<GetIDInvoiceManagementCommandHandler> _logger;

        public GetIDInvoiceManagementCommandHandler(ILogger<GetIDInvoiceManagementCommandHandler> logger, IMapper mapper, IInvoiceManagementRepository invoiceManagementRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _invoiceManagementRepository = invoiceManagementRepository;
        }




        public async Task<ApiResult<InvoiceManagement>> Handle(GetIDInvoiceManagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有生产工单
                var InvoiceManagements = await _invoiceManagementRepository.GetAsync(x => x.Invoicemanagementid == request.Invoicemanagementid);

                // 使用 AutoMapper 进行对象映射
                var InvoiceManagementReposnse = _mapper.Map<InvoiceManagement>(InvoiceManagements);

                // 返回成功结果
                return ApiResult<InvoiceManagement>.Success(InvoiceManagementReposnse, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<InvoiceManagement>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
